import React, { useReducer } from 'react'
import {View, Button} from "@tarojs/components";
import './index.scss'


const initValue = { name: 'liulongbin', age: 16 }
type UserType = typeof initValue
// 父组件
export const Father: React.FC = () => {

  const initAction = (initState: UserType) => {
    // 把 return 的对象，作为 useReducer 的初始值
    return { ...initState, age: Math.round(Math.abs(initState.age)) || 18 }
  }

  const reducer = (prevState: UserType, action: UserType) => {
    console.log('触发了 reducer 函数', prevState, action)
    return {...prevState, ...action}
  }

  const [userInfo, updateUserInfo] = useReducer(reducer, initValue, initAction)

  const changeInfo = () => {
    updateUserInfo({name: 'jiangang', age: ++userInfo.age})
  }

  return (
    <View>
      <Button>修改 name 的值{userInfo.name}{userInfo.age}</Button>
      <View className="father">
        <Button size="mini" onClick={changeInfo}>触发dispatch</Button>
        <Son1 {...userInfo} updateUser={updateUserInfo}/>
        <Son2 {...userInfo}/>
      </View>
    </View>
  )
}
// 子组件1
const Son1: React.FC<UserType & { updateUser: React.Dispatch<UserType> }> = (props) => {
  const { updateUser, ...user } = props
  return <View className="son1">
    <View>{JSON.stringify(user)}</View>
    <Button onClick={() => updateUser({name: 'son', age: 1})} size='mini'>子组件更新</Button>
  </View>
}

// 子组件2
const Son2: React.FC<UserType> = (user) => {
  return <View className="son2">{JSON.stringify(user)}</View>
}

export default Father
